import React, { Component } from 'react';
import { Form, Button, Pagination, message, Modal, Input } from 'antd';
import moment from 'moment';

import RESTClient from '../../api/client.js';

import './style.css';

const FormItem = Form.Item;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};


class Repair extends Component{
  constructor(props){
    super(props);
    this.state={
      dataSource: [],
      showDatas: [],
      total: 0,
      currentPage: 1,
      intervalId: null,
      modalData: {},
      modalVisible: false
    }
  }
  componentWillMount() {
    this.getRepairData();
    var intervalId = setInterval(()=>{
      this.getRepairData()
    },120000);
    this.setState({
      intervalId: intervalId
    })
  }
  getRepairData() {
    new RESTClient().XCXQuery({type: 'repair'},function(datas){
      console.log(1111,datas);
      this.setState({
        dataSource: datas,
        showDatas: datas.slice(10*(this.state.currentPage-1),10*this.state.currentPage),
        total: datas.length
      })
    }.bind(this))
  }
  componentWillUnmount() {
    clearInterval(this.state.intervalId);
  }
  pageChange(value) {
    var dataSource = this.state.dataSource;
    this.setState({
      currentPage: value,
      showDatas: dataSource.slice(10*(value-1),10*value),
    })
  }
  setStatus(id,status) {
    console.log(id,status);
    var data = JSON.stringify({
      id: id,
      status: !status
    })
    new RESTClient().XCXSetStatus({data: data},function(datas){
      // console.log(1111,datas);
      if(datas === 'success'){
        message.success("修改成功");
        var dataSource = this.state.dataSource.slice(0), showDatas = this.state.showDatas.slice(0);
        for (let i = 0; i < dataSource.length; i++) {
          if(dataSource[i].objectId === id){
            dataSource[i].status = !status;
            break;
          }
        }
        for (let i = 0; i < showDatas.length; i++) {
          if(showDatas[i].objectId === id){
            showDatas[i].status = !status;
            break;
          }
        }
        this.setState({
          dataSource: dataSource,
          showDatas: showDatas
        })
      }
    }.bind(this))
  }
  openModal(data) {
    if(data.status) {
      this.props.form.setFieldsValue({
        repairId: data.repairId||'',
        finishedTime: data.finishedTime||'',
        fitterName: data.fitterName||'',
        actionDesc: data.actionDesc||''
      })
    }
    this.setState({
      modalData: data,
      modalVisible: true
    })
  }
  handleOk() {
    if(this.state.modalData.status) {
      message.error("请勿重复提交");
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        var data = values;
        data.id = this.state.modalData.objectId;
        data.status = !this.state.modalData.status;
        new RESTClient().XCXSetStatus({data: JSON.stringify(data)},function(datas){
          // console.log(1111,datas);
          if(datas === 'success'){
            message.success("修改成功");
            var dataSource = this.state.dataSource.slice(0), showDatas = this.state.showDatas.slice(0);
            for (let i = 0; i < dataSource.length; i++) {
              if(dataSource[i].objectId === data.id){
                dataSource[i].status = data.status;
                dataSource[i].repairId = data.repairId;
                dataSource[i].actionDesc = data.actionDesc;
                dataSource[i].finishedTime = data.finishedTime;
                dataSource[i].fitterName = data.fitterName;
                break;
              }
            }
            for (let i = 0; i < showDatas.length; i++) {
              if(showDatas[i].objectId === data.id){
                showDatas[i].status = data.status;
                showDatas[i].repairId = data.repairId;
                showDatas[i].actionDesc = data.actionDesc;
                showDatas[i].finishedTime = data.finishedTime;
                showDatas[i].fitterName = data.fitterName;
                break;
              }
            }
            this.setState({
              dataSource: dataSource,
              showDatas: showDatas,
              modalData: {},
              modalVisible: false
            })
          }
        }.bind(this))
      } else {
        message.error("请检查所有必填字段");
      }
    });
  }
  handleCancel() {
    this.props.form.setFieldsValue({
      repairId: '',
      finishedTime: '',
      fitterName: '',
      actionDesc: ''
    })
    this.setState({
      modalData: {},
      modalVisible: false
    })
  }
  render(){
    const { getFieldDecorator } = this.props.form;
    const { modalData } = this.state;
    return(
      <div className="sence-div">
        <table className="sence-table" cellSpacing="0">
          <thead>
            <tr>
              <th className="sence-th">报修时间</th>
              <th className="sence-th">设备号</th>
              <th className="sence-th">姓名</th>
              <th className="sence-th">联系电话</th>
              <th className="sence-th">故障类型（标签选择）</th>
              <th className="sence-th">故障描述</th>
              <th className="sence-th">当前状态</th>
              <th className="sence-th">操作</th>
            </tr>
          </thead>

          <tbody>
            {this.state.showDatas.map(function(data,index){
              return(
                <tr key={index} style={data.status?{}:{fontWeight:'bold'}}>
                  <td className="sence-td">{moment(data.createdAt).format("YYYY-MM-DD HH:mm:ss")||''}</td>
                  <td className="sence-td">{data.equNumber||''}</td>
                  <td className="sence-td">{data.name}{(data.gender==="male"?"先生":"女士")||''}</td>
                  <td className="sence-td">{data.phone||''}</td>
                  <td className="sence-td" style={{width:280}}>{data.tags.join(',')||'未选择'}</td>
                  <td className="sence-td" style={{width:280}}>{data.desc||'未填写'}</td>
                  <td className="sence-td">{data.status?"已处理":"未处理"}</td>
                  <td className="sence-td">
                    {/*<Button onClick={(id,status)=>this.setStatus(data.objectId,data.status)} type="primary">{data.status?"标记为未处理":"标记为已处理"}</Button>*/}
                    <Button onClick={(e)=>this.openModal(data)} type="primary">{data.status?"查看维修记录":"提交维修记录"}</Button>
                  </td>
                </tr>
              )
            }.bind(this))}
          </tbody>
        </table>
        <div className="sence-page">
          <Pagination style={{textAlign:'right'}} current={this.state.currentPage} pageSize={10}
                      total={this.state.total} onChange={current=>this.pageChange(current)} />
        </div>
        <Modal
          title="提交维修结果"
          okText="提交"
          cancelText="取消"
          width="50%"
          visible={this.state.modalVisible}
          onOk={()=>this.handleOk()}
          onCancel={()=>this.handleCancel()}
        >

          <FormItem
            {...formItemLayout}
            label="设备编号"
          >
            <Input disabled value={modalData.equNumber||''}/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="报修时间"
          >
            <Input disabled value={modalData.createdAt?moment(modalData.createdAt).format("YYYY-MM-DD HH:mm:ss"):''} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="报修内容"
          >
            <TextArea disabled autosize={true} value={(modalData.tags?(modalData.tags.join(',')+((modalData.tags.length>0?'；':''))):'') + (modalData.desc||'')} />
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="维修工单"
          >
            {getFieldDecorator('repairId', {
              rules: [{
                required: true, message: '请填写维修工单',
              }],
            })(
              <Input disabled={modalData.status} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="完成时间"
          >
            {getFieldDecorator('finishedTime', {
              rules: [{
                required: true, message: '请填写完成时间',
              }],
            })(
              <Input disabled={modalData.status} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="维修工程师"
          >
            {getFieldDecorator('fitterName', {
              rules: [{
                required: true, message: '请填写维修工程师',
              }],
            })(
              <Input disabled={modalData.status} />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="维修内容"
          >
            {getFieldDecorator('actionDesc', {
              rules: [{
                required: true, message: '请填写维修内容',
              }],
            })(
              <Input disabled={modalData.status} />
            )}
          </FormItem>
        </Modal>
      </div>
    )
  }
}

export default Form.create()(Repair);
